//
//  RateQueryCell.m
//  ImGuider
//
//  Created by 李陆涛 on 2018/2/26.
//  Copyright © 2018年 imguider. All rights reserved.
//

#import "RateQueryCell.h"
#import <IQUITextFieldView+Additions.h>

@interface RateQueryCell ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UIView *tagView;

@property (weak, nonatomic) IBOutlet UIView *currencyView;

@property (weak, nonatomic) IBOutlet UIImageView *nationalFlagImageView;

@property (weak, nonatomic) IBOutlet UILabel *currencyLabel;
@property (weak, nonatomic) IBOutlet UILabel *currencyNameLabel;
@property (weak, nonatomic) IBOutlet UITextField *moneyTF;


@end

@implementation RateQueryCell

- (void)awakeFromNib {
    [super awakeFromNib];
    
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    self.moneyTF.keyboardType = UIKeyboardTypeDecimalPad;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadRate:) name:kRateModelValueChangeNotif object:nil];
    self.tagView.hidden = YES;
    
    self.nationalFlagImageView.layer.cornerRadius = 15.0f;
    self.nationalFlagImageView.layer.borderWidth = 1.0f;
    self.nationalFlagImageView.layer.borderColor = kBGColor.CGColor;
    
    
    
    
    @weakify(self);
    [self.currencyView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
        @strongify(self);
        
        if ([_delegate respondsToSelector:@selector(rateQueryCell:changedMode:)]) {
            
            [_delegate rateQueryCell:self changedMode:self.mode];
        }
        
    }]];
}

- (void)reloadRate:(NSNotification *)notif {
    
    RateMode *mode = notif.userInfo[kRateModelValueChangeKey];
    
    if (!mode) {
        return;
    }
    
    if ([self.mode.code isEqualToString:mode.code]) {
        return;
    }
    
    self.mode.baseMoney = mode.baseMoney;
    
    [self setMoneyWithMoney:self.mode.realMoney];
}

- (void)setMode:(RateMode *)mode {
    
    _mode = mode;
    
    [self.nationalFlagImageView setImageURL:[NSURL URLWithString:mode.pictures] placeholderImage:kPlaceholderSqu];
    self.currencyLabel.text = mode.code;
    self.currencyNameLabel.text = mode.smartName;
    
    [self setMoneyWithMoney:mode.realMoney];
}

- (void)setMoneyWithMoney:(NSString *)money {
    
    if (!money || money.length == 0) {
        
        self.moneyTF.text = nil;
        self.moneyTF.placeholder = @(100 * self.mode.rate.floatValue).stringValue;
    } else {
        self.moneyTF.text = money;
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    
    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    
    NSLog(@"--------%@",toBeString);
    
    if ([_delegate respondsToSelector:@selector(rateQueryCell:changedValue:)]) {
        
        [_delegate rateQueryCell:self changedValue:toBeString];
    }
    
    return YES;
}

@end
